public class CaseEmailControl {
	//anti-recursion classes
	private static boolean alreadyPopulatedEmail = false;
    public static boolean hasAlreadyPopulatedEmail() 
    {
    	return alreadyPopulatedEmail;
    }
    public static void setAlreadyPopulatedEmail() 
    {
    	alreadyPopulatedEmail = true;
    }
    //end anti-recursion classes

	//this method populates the standard email fields on the case used for communication.
	Public static void populateEmailFields (case[] cases)
	{
		if (!CaseEmailControl.hasAlreadyPopulatedEmail()) 
		{
			List<case> updateCases = new List<case>();
			Set<id> caseIdSet = New Set<id>();
			system.debug(cases);
			for (integer i = 0; i < cases.size(); i++)
			{
					caseIdSet.add(cases[i].id);				
			}
			if (caseIdSet.size()>0)
			{
				for(case c : [Select Case_Email_ESC_Contact__c, Case_Email_Case_Contact__c, Case_Email_Account_Contact__c, Contact.Email, Account.Case_Email__c, ESC_Contact__r.Email, IsVisibleInSelfService From Case  where id in :caseIdSet])
				{
					integer fieldUpdateCount = 0;
					if (c.Case_Email_ESC_Contact__c != c.ESC_Contact__r.Email)
					{
						c.Case_Email_ESC_Contact__c = c.ESC_Contact__r.Email;
						fieldUpdateCount ++;
					}
					if (c.Case_Email_Case_Contact__c != c.Contact.Email) if(c.IsVisibleInSelfService == true)
					{
						c.Case_Email_Case_Contact__c = c.Contact.Email;
						fieldUpdateCount ++;
					}
					if (c.Case_Email_Case_Contact__c != Null) if(c.IsVisibleInSelfService == false)
					{
						c.Case_Email_Case_Contact__c = Null;
						fieldUpdateCount ++;
					}
					if (c.Case_Email_Account_Contact__c != c.Account.Case_Email__c) if(c.IsVisibleInSelfService == true)
					{
						c.Case_Email_Account_Contact__c = c.Account.Case_Email__c;
						fieldUpdateCount ++;
					}
					if (c.Case_Email_Account_Contact__c != Null) if(c.IsVisibleInSelfService == false)
					{
						c.Case_Email_Account_Contact__c = Null;
						fieldUpdateCount ++;
					}
					if (fieldUpdateCount > 0)
					{
						updateCases.add(c);
					}
				}
				update updateCases;	
				setAlreadyPopulatedEmail();
			}
		}	
	}

}